package com.huarun.common.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

/**
 * Created by YangJi on 2017/5/23.
 */
public class WechatLogin {



	public static void main(String[] args) {
		// String returnUrl="{info={nickName=Jony, gender=1, language=zh_CN, city=深圳,
		// province=广东, country=中国,
		// avatarUrl=https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIMgyoP2nl9cCAelNcET4zEJmVKKmYLlpLSyl6fIWYgxnZVolFyOwZuLUn8JjphAsWWoHUzR2oJww/132},
		// encryptedData=9kTUfzLN7G/UqhtP2/L5js4dUVTQ/8LhhTsaUVA36SYoGLESPyRNC4b4XDBWwSPk8n3q1cB0+jydCdqZCycvzm8VBaO09+QSVY6cEvQfYXrkx2FAA0RVu9kgoPP2y+arR09UODY7jPptcZKeKwrn1BYUE9hutQcCAc5QuKcmNnJWT2xfQi+CXgUePUvPMZZ9rvTRKz2NGetDnTcwU0uVNCSZwDhL5l47vbBVWpNRJm6cCKTsgWVu2SF/I6HFKl/wZd56AN5ZXCCCLloAE+HusqkrwUKRG9hGtf0K9t0Z/3mVElfnYGq4zU09RjwlYocTzei/ip2WZkz+nZjQiyW9TvmmGKOAYsWYONrM7m0D/RAjWHXLZ7/Y8uSqMHBgyHDX1qDcqSKfrpqzuEtl5wO0T7k60+f8hMPqFlTwWXm1SXnoMGcqqptLIjZbxMVvENLUtCwRfjbDiyRn4btWofEDtg==,
		// iv=8BKghW+CP8u+0yiTOPyNug==}";
		String encryptedData = "eZAZMCDbvxksoA8JbNlpZ43Df9dTqFoP11CFcDCrZSGt2zo4NZY7j+XC2MA5+1IJNLiW4pxQgKnNGSPLxV7ySQpa8UuwyINIlpT9slGxJ9gAJoPlcXf9DmFQUClpxu4tYg6bIJeGw3eByyZVyEsqqn7GUX5bfawt6bzHJDHyBgIin91tZOVUdOu4rs2ZxjebQVzFAJz1EYlCPqtziy2Eeg==";
		String iv = "8sxyTYRYHn6xPts44TU+tA==";
		JSONObject phone = WechatGetUserInfoUtil.getUserInfo(encryptedData, "CrvJ+sB9OshRCXN55M7I8A==", iv);
		System.out.println(phone.toString());
	}

	

	/**
	 * 获得code后获取access_token { "access_token":"ACCESS_TOKEN", "expires_in":7200,
	 * "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
	 * 
	 * @param code
	 */
	public String getAccessToken(String code) {
		// https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
		try {
			String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
			String param = "appid=" + Constant.WX_APPID + "&secret=" + Constant.WX_SECRET + "&code=" + code
					+ "&grant_type=authorization_code";
			System.out.println("Constant.WX_APPID:"+Constant.WX_APPID);
			return sendGet(url, param);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获得code后获取access_token { "access_token":"ACCESS_TOKEN", "expires_in":7200,
	 * "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
	 * 
	 * @param code
	 */
	public String getSessionKey(String code) {
		// https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
		try {
			String url = "https://api.weixin.qq.com/sns/jscode2session";
			String param = "appid=" + Constant.WX_APPID + "&secret=" + Constant.WX_SECRET + "&code=" + code
					+ "&grant_type=authorization_code&js_code=" + code;
			
			System.out.println("Constant.WX_APPID:"+Constant.WX_APPID);
			return sendGet(url, param);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取微信用户信息
	 * https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
	 * { "openid":"OPENID", "nickname":"NICKNAME", "sex":1, "province":"PROVINCE",
	 * "city":"CITY", "country":"COUNTRY", "headimgurl":
	 * "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
	 * "privilege":[ "PRIVILEGE1", "PRIVILEGE2" ], "unionid": "
	 * o6_bmasdasdsad6_2sgVt7hMZOPfL" }
	 * 
	 * @param access_token
	 * @param openId
	 * @return
	 */
	public String getUserInfo(String access_token, String openId) {
		return sendGet("https://api.weixin.qq.com/cgi-bin/user/info",
				"access_token=" + access_token + "&openid=" + openId);
	}

	/**
	 * 发送GET请求
	 * 
	 * @param url
	 * @param param
	 * @return
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			URLConnection connection = realUrl.openConnection();
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.connect();
			Map<String, List<String>> map = connection.getHeaderFields();
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

}
